//
//  MOSetUpViewController.m
//  MobileOffice
//
//  Created by 晓 on 2019/5/30.
//  Copyright © 2019 com.idolmedia. All rights reserved.
//

#import "MOSetUpViewController.h"
#import "MOSetUpViewCell.h"
#import "AppDelegate.h"
#import "MOPersonSetViewController.h"
#import "MOPersonInfoViewController.h"
#import "MOAccountRelevanceViewController.h"
#import "MOVersionInfoViewController.h"

@interface MOSetUpViewController ()<UITableViewDelegate,UITableViewDataSource,UIActionSheetDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) UIView *headerView;

@property (nonatomic, strong) UIButton *userPhotoButton;

@property (nonatomic, strong) UILabel *userNameLabel;

@property (nonatomic, strong) UILabel *userPhoneNumberLabel;

@property (nonatomic, strong) NSArray *iconImageArr;

@property (nonatomic, strong) NSArray *titleArray;

@property (nonatomic, strong) NSString *haveNewVersion;

@end

@implementation MOSetUpViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
    [self getIpaInfoData];
}
//初始化view
- (void)initView{
    self.tableView.tableHeaderView = self.headerView;
    [self.view addSubview:self.tableView];
}

-(void)getIpaInfoData
{
    //
    NSString *postUrl = [NSString stringWithFormat:@"%@?apkType=IOS&authorization=%@",APKINFO_GETAPKINFO_URL,[NSString URLEncodedString:[MOUser sharedMOUser].token]];
    
    [PPNetworkHelper GET:postUrl parameters:@{} success:^(id responseObject) {
        NSLog(@"版本信息:%@",responseObject);
        
        NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
        NSString *app_version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
        NSInteger current = [[app_version stringByReplacingOccurrencesOfString:@"." withString:@""] integerValue];
        NSInteger new = [[[NSString passNullForString:responseObject[@"apk_version"]] stringByReplacingOccurrencesOfString:@"." withString:@""] integerValue];
        if (new>current) {//有新版本
            self.haveNewVersion = [NSString stringWithFormat:@"%ld",(long)new];
            [self.tableView reloadData];
        }
        
    } failure:^(NSError *error) {
        
        [[ADShowMessage shareShowMessage] showTextOnly:[error localizedDescription] showInView:WINDOW];
    }];
}

#pragma mark -- 退出登录
-(void)clickOutLogin
{
    MOHintView *hintView = [[MOHintView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) andContentStr:@"确定要退出登录吗？"];
    __weak typeof (self)weakSelf = self;
    hintView.clickSureButtonBlock = ^{
        [weakSelf removeUserData];
    };
    [WINDOW addSubview:hintView];
}


-(void)removeUserData
{
    MOUser *user = [MOUser sharedMOUser];
    NSString *str = user.userName;
    
    [MOUser clearUser];
    [[NSUserDefaults standardUserDefaults]setObject:str forKey:@"outName"];
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [appDelegate outLogin];
    
    NSString *postUrl = [NSString stringWithFormat:@"%@?token=%@&userId=%@",A_OUT_URL,[NSString URLEncodedString:[MOUser sharedMOUser].token],user.user_id];
    
    [PPNetworkHelper GET:postUrl parameters:@{} success:^(id responseObject) {
        NSLog(@"退出登录:%@",responseObject);
    } failure:^(NSError *error) {
        
        [[ADShowMessage shareShowMessage] showTextOnly:[error localizedDescription] showInView:WINDOW];
    }];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MOSetUpViewCell *setCell = [MOSetUpViewCell cellWithTableView:tableView];
    setCell.iconImageView.image = IMAGE(self.iconImageArr[indexPath.section]);
    setCell.titleLabel.text = self.titleArray[indexPath.section];
    if (indexPath.section == 1 && [self.haveNewVersion integerValue]>0) {
        setCell.updatePromptLabel.hidden = NO;
    }
    else{
        setCell.updatePromptLabel.hidden = YES;
    }
    return setCell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kHConversions(54);
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        return 1;
    }
    else {
        return 10;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section==3) {
        return kHConversions(54)+10;
    }else{
        return 0.0000001;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section==3) {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, kHConversions(45))];
        view.backgroundColor = KGrayColor_f8f8f8;
        
        UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(0, 10, SCREEN_WIDTH, kHConversions(45))];
        [button setTitle:@"退出登录" forState:UIControlStateNormal];
        button.titleLabel.font = FONT_SIZE(16);
        [button setTitleColor:KBlackColor_2A2A2A forState:UIControlStateNormal];
        [button setBackgroundColor:[UIColor whiteColor]];
        [button addTarget:self action:@selector(clickOutLogin) forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:button];
        
        return view;
    }else{
        return nil;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        MOPersonSetViewController *vc = [[MOPersonSetViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    else if (indexPath.section == 1){
        MOVersionInfoViewController *versionInfoVC = [[MOVersionInfoViewController alloc] init];
        versionInfoVC.version = self.haveNewVersion;
        [self.navigationController pushViewController:versionInfoVC animated:YES];
        self.haveNewVersion = @"";
    }
    else if (indexPath.section == 2){
        MOPersonInfoViewController *personInfoVC = [[MOPersonInfoViewController alloc] init];
        [self.navigationController pushViewController:personInfoVC animated:YES];
    }
    else if (indexPath.section == 3){
        MOAccountRelevanceViewController *accountRelevanceVC = [[MOAccountRelevanceViewController alloc] init];
        [self.navigationController pushViewController:accountRelevanceVC animated:YES];
    }
}

- (void)setupBorderAndRadiusForView:(UIView *)view{
    
    // 渐变色 layer
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = view.bounds;
    gradientLayer.colors = @[(__bridge id)[[UIColor redColor] colorWithAlphaComponent:1.0].CGColor,
                             (__bridge id)[[UIColor greenColor] colorWithAlphaComponent:1.0].CGColor,
                             (__bridge id)[[UIColor blueColor] colorWithAlphaComponent:1.0].CGColor];
    gradientLayer.startPoint = CGPointMake(.0, .0);
    gradientLayer.endPoint = CGPointMake(.0, 1.0);
    [view.layer addSublayer:gradientLayer];
    
    // 图形绘制 layer
    CGFloat lineWidth = 1.0;
    CGFloat rectSide = view.bounds.size.width - lineWidth;
    UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:(CGRect){lineWidth / 2, lineWidth / 2, rectSide, rectSide}];
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = path.CGPath;
    shapeLayer.fillColor = [UIColor clearColor].CGColor;
    shapeLayer.strokeColor = [UIColor whiteColor].CGColor;
    shapeLayer.lineWidth = lineWidth;
    gradientLayer.mask = shapeLayer;
    
}



#pragma mark -懒加载
- (UIView *)headerView{
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, kHConversions(175))];
        _headerView.backgroundColor = KWhiteColor;
        
        UIView *backImageView = [[UIView alloc]initWithFrame:CGRectMake(15, 15, SCREEN_WIDTH - 30, kHConversions(160-25))];
        [backImageView shadow_card];
        backImageView.backgroundColor = [UIColor whiteColor];
//        backImageView.image = IMAGE(@"setUp_shadow");
        
        self.userPhotoButton = [[UIButton alloc] initWithFrame:CGRectMake(20, 0, kHConversions(64), kHConversions(64))];
        self.userPhotoButton.centerY = backImageView.height/2;
        self.userPhotoButton.layer.masksToBounds = YES;
        self.userPhotoButton.layer.cornerRadius = kHConversions(64)/2;
        self.userPhotoButton.layer.borderWidth = 0.00001;
        [self.userPhotoButton setImage:IMAGE(@"user_default") forState:UIControlStateNormal];
//        [self setupBorderAndRadiusForView:self.userPhotoButton];
        

        MOUser *user = [MOUser sharedMOUser];
        
        self.userNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.userPhotoButton.frame) + 12, CGRectGetMinY(self.userPhotoButton.frame) + 12, CGRectGetWidth(backImageView.frame) - 40 - kHConversions(64) - 12, kHConversions(16))];
        self.userNameLabel.text = user.name;
        self.userNameLabel.textColor = KFontBlackColor;
        if (@available(iOS 8.2, *)) {
            self.userNameLabel.font = [UIFont systemFontOfSize:19 weight:UIFontWeightMedium];
        } else {
            self.userNameLabel.font = [UIFont boldSystemFontOfSize:19];
        }
        
        
        self.userPhoneNumberLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(self.userNameLabel.frame), CGRectGetMaxY(self.userPhotoButton.frame) - 12 - kHConversions(12), CGRectGetWidth(self.userNameLabel.frame), kHConversions(12))];
        self.userPhoneNumberLabel.text = user.phone;
        self.userPhoneNumberLabel.font = FONT_SIZE(12);
        self.userPhoneNumberLabel.textColor = KFontLightColor;
        
        [_headerView addSubview:backImageView];
        [backImageView addSubview:self.userPhotoButton];
        [backImageView addSubview:self.userNameLabel];
        [backImageView addSubview:self.userPhoneNumberLabel];
    }
    return _headerView;
}

-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - TabbarHeight) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = KGrayColor_f8f8f8;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}

- (NSArray *)iconImageArr{
    if (!_iconImageArr) {
        _iconImageArr = @[@"setUp_set",@"setUp_updata",@"setUp_userInfo",@"setUp_contactAccount"];
    }
    return _iconImageArr;
}

- (NSArray *)titleArray{
    if (!_titleArray) {
        _titleArray = @[@"设置",@"检查更新",@"个人信息",@"账号关联"];
    }
    return _titleArray;
}

@end
